package exabase.data;

import static org.junit.Assert.assertEquals;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.junit.Before;
import org.junit.Test;

public class DataPersistenceTest {

	@Before
	public void setUp() throws Exception {
		clearDataStore();
	}

	private void clearDataStore() {
		DataStore.instance = null;
	}

	@Test
	public void testParseEntireDocument() throws JAXBException {
		JAXBContext ctx = JAXBContext
				.newInstance(new Class[] { exabase.auto.data.DataStore.class });
		Unmarshaller um = ctx.createUnmarshaller();
		exabase.auto.data.DataStore dataStore = (exabase.auto.data.DataStore) um
				.unmarshal(new File("testFiles/xml/data1.xml"));
		assertEquals("the fileURL should be correct", "fileURL1", dataStore
				.getData().get(0).getFileURL());
		assertEquals("the hash should be correct", "hash1", dataStore.getData()
				.get(0).getHash());
	}

	@Test
	public void testPersistenceGet() {
		DataPersistence.getInstance().getDataFrom("testFiles/xml/data1.xml");
		assertEquals("there should be one data", 1, DataStore.getInstance()
				.getDataSet().size());
		assertEquals("the fileURL should be correct", "fileURL1", DataStore
				.getInstance().getDataSet().iterator().next().getFileURL());
		assertEquals("the hash should be correct", "hash1", DataStore
				.getInstance().getDataSet().iterator().next().getHash()
				.toString());
	}

	@Test
	public void testPersistencePut() {
		Hash hash = new Hash("hash");
		DataStore.getInstance().addData("URL", hash);
		DataPersistence.getInstance().putDataTo("tmpTest1.xml");
		clearDataStore();
		DataPersistence.getInstance().getDataFrom("tmpTest1.xml");
		assertEquals("there should be one data", 1, DataStore.getInstance()
				.getDataSet().size());
		assertEquals("the fileURL should be correct", "URL", DataStore
				.getInstance().getDataSet().iterator().next().getFileURL());
		assertEquals("the hash should be correct", hash.toString(), DataStore
				.getInstance().getDataSet().iterator().next().getHash().toString());
	}
}
